package org.jeecg.modules.mes.order.controller;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.mes.client.StockClient;
import org.jeecg.modules.mes.order.entity.ImpApplyBill;
import org.jeecg.modules.mes.order.entity.MesOrderPurchase;
import org.jeecg.modules.mes.order.entity.MesPurchaseItem;
import org.jeecg.modules.mes.order.service.IMesOrderPurchaseService;
import org.jeecg.modules.mes.order.service.IMesPurchaseItemService;
import org.jeecg.modules.mes.storage.entity.MesStorageWholesale;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 订单管理—采购订单
 * @Author: jeecg-boot
 * @Date: 2020-10-19
 * @Version: V1.0
 */
@Api(tags = "订单管理—采购订单")
@RestController
@RequestMapping("/order/mesOrderPurchase")
@Slf4j
public class MesOrderPurchaseController extends JeecgController<MesOrderPurchase, IMesOrderPurchaseService> {

    @Autowired
    private IMesOrderPurchaseService mesOrderPurchaseService;

    @Autowired
    private IMesPurchaseItemService mesPurchaseItemService;
    @Autowired
    private StockClient stockClient;




    /*---------------------------------主表处理-begin-------------------------------------*/

    /**
     * 分页列表查询
     *
     * @param mesOrderPurchase
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "订单管理—采购订单-分页列表查询")
    @ApiOperation(value = "订单管理—采购订单-分页列表查询", notes = "订单管理—采购订单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(MesOrderPurchase mesOrderPurchase,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<MesOrderPurchase> queryWrapper = QueryGenerator.initQueryWrapper(mesOrderPurchase, req.getParameterMap());
        queryWrapper.orderByDesc("create_time");
        Page<MesOrderPurchase> page = new Page<MesOrderPurchase>(pageNo, pageSize);
        IPage<MesOrderPurchase> pageList = mesOrderPurchaseService.page(page, queryWrapper);
        if (pageList.getSize() != 0) {
            //如果上传关务系统的状态为空，则设置状态为0（预防作用）
            List<MesOrderPurchase> purchaseList = pageList.getRecords();
            for (MesOrderPurchase purchase : purchaseList) {
                if (StringUtils.isBlank(purchase.getImportState())) {
                    purchase.setImportState("0");//设置上传关务系统的状态为0
                    mesOrderPurchaseService.updateById(purchase);
                }
                //通过采购订单id，获取采购订单子表数据
                String orderId = purchase.getId();
                QueryWrapper<MesPurchaseItem> wrapper = new QueryWrapper<>();
                wrapper.eq("purchase_id", orderId);
                List<MesPurchaseItem> purchaseItemList = mesPurchaseItemService.list(wrapper);
                if (purchaseItemList.size() != 0) {
                    float totalPrice = 0;
                    for (MesPurchaseItem purchaseItem : purchaseItemList) {
                        //如果采购明细的价格不为空，则它们的总和为销售订单的总价
                        if (StringUtils.isNotBlank(purchaseItem.getGrossPrice())) {
                            String grossPrice = purchaseItem.getGrossPrice();//单价
                            totalPrice += Float.parseFloat(grossPrice);
                        }
                    }
                    purchase.setTotalPrice(totalPrice + "");//总价
                    mesOrderPurchaseService.updateById(purchase);
                }
            }
        }
        IPage<MesOrderPurchase> pageList1 = mesOrderPurchaseService.page(page, queryWrapper);
        return Result.ok(pageList1);
    }

    // 生成订单流水号
    public String getOrderNum() {
        String prefix = "MES";
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        int random = RandomUtils.nextInt(90) + 10;
        String value = prefix + format.format(new Date()) + random;
        return value;
    }

    @AutoLog(value = "采购订单-进口申请单-生成")
    @ApiOperation(value = "进口申请单-生成", notes = "根据采购单id生成进口申请单")
    @GetMapping(value = "/generateImport")
    public Result<?> generateImport(@RequestParam(name = "purchaseId", required = true) String purchaseId) {
        MesOrderPurchase purchase = mesOrderPurchaseService.getById(purchaseId);

        if (purchase != null) {
            if ("库存初始".equals(purchase.getOrderType())) { //库存初始的不上传关务
                return Result.error("订单类型为库存初始的不可以生成申请单！");
            }
            if ("1".equals(purchase.getImportState())) {//是否已生成进口申请单，若已生成，则为1,反之为0
                return Result.error("已生成过进口申请单！");
            }
            QueryWrapper<MesPurchaseItem> wrapper = new QueryWrapper<>();
            wrapper.eq("purchase_id", purchase.getId());
            List<MesPurchaseItem> purchaseItemList = mesPurchaseItemService.list(wrapper);
            if (purchaseItemList.size() != 0) {
                List<ImpApplyBill> billlist = new ArrayList<>();
                int count1 = 0;
                for (MesPurchaseItem purchaseItem : purchaseItemList) {
                    count1 += 1;
                    //实例化format，格式为“000”
                    Format f1 = new DecimalFormat("000");
                    //将1变为001
                    String count = f1.format(count1);
                    ImpApplyBill impApplyBill = new ImpApplyBill();
                    impApplyBill.setGwId(IdUtil.simpleUUID());
                    impApplyBill.setInvoiceNo(purchase.getOrderCode());
                    impApplyBill.setImgExgFlag(purchaseItem.getImgExgFlag());
                    impApplyBill.setItemNo(count1);
                    impApplyBill.setMaterial(purchaseItem.getMaterielCode());//料号
                    impApplyBill.setMaterialName(purchaseItem.getMaterielName());//品名
                    impApplyBill.setMaterialGuige(purchaseItem.getMaterielGauge());//规格
                    impApplyBill.setOptLock(0);
                    SimpleDateFormat Dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
                    String dateTime = Dateformat.format(new Date());
                    impApplyBill.setSectionNo(dateTime + "001");//批次号
                    impApplyBill.setCompanyCode("500666002U");
//						 impApplyBill.setUploadDate(new java.util.Date());//改为上传关务的时候修改该字段
                    if (StringUtils.isBlank(purchaseItem.getGrossPrice())) {
                        purchaseItem.setGrossPrice("0");
                    }
                    impApplyBill.setPrice(Double.parseDouble(purchaseItem.getGrossPrice()));//企业单件
                    if (StringUtils.isBlank(purchase.getTotalPrice())) {
                        purchase.setTotalPrice("0");
                    }
                    impApplyBill.setAmount(Double.parseDouble(purchase.getTotalPrice()));//企业总价
                    impApplyBill.setCurr(purchase.getCurrency());//币制
                    impApplyBill.setCompanyMergerKey("");

                    SimpleDateFormat Dateformatter = new SimpleDateFormat("yyyy/M/d");
                    String docketTime = Dateformatter.format(new Date());
                    impApplyBill.setInvoiceDate(docketTime);//票据日期
                    if (StringUtils.isBlank(purchaseItem.getPalletNum())) {
                        purchaseItem.setPalletNum("0");
                    }
                    impApplyBill.setPalletNum(Integer.parseInt(purchaseItem.getPalletNum()));//板数
                    if (StringUtils.isBlank(purchaseItem.getPcs())) {
                        purchaseItem.setPcs("0");
                    }
                    impApplyBill.setPcs(Integer.parseInt(purchaseItem.getPcs()));//件数
                    impApplyBill.setWrap(purchaseItem.getWrap());//包装种类
                    impApplyBill.setContainerNo(purchaseItem.getContainerNo());//箱号
                    if (StringUtils.isBlank(purchaseItem.getPurchaseNum())) {
                        purchaseItem.setPurchaseNum("0");
                    }
                    impApplyBill.setQty(Double.parseDouble(purchaseItem.getPurchaseNum()));//企业数量
                    if (StringUtils.isBlank(purchaseItem.getNetWeight())) {
                        purchaseItem.setNetWeight("0");
                    }
                    impApplyBill.setNetWeight(Double.parseDouble(purchaseItem.getNetWeight()));//净重
                    if (StringUtils.isBlank(purchaseItem.getGrossWeight())) {
                        purchaseItem.setGrossWeight("0");
                    }
                    impApplyBill.setGrossWeight(Double.parseDouble(purchaseItem.getGrossWeight()));//毛重
                    impApplyBill.setScmCoc(purchase.getSupplierName());//客户/供应商
                    impApplyBill.setClientCode(purchaseItem.getClientCode());
                    impApplyBill.setProductCode(purchaseItem.getProductCode());
                    impApplyBill.setImpApplyState("未上传");
                    billlist.add(impApplyBill);

                }

                //设置采购订单主表状态为1：已生成
                purchase.setImportState("1");
                mesOrderPurchaseService.saveImpUpdateState(purchase, billlist);
                System.err.println("进口申请单导入完成---");
            } else {
                return Result.error("没有找到采购订单子表的数据！请检查！");
            }
        } else {
            return Result.ok("数据已全部生成进口申请单！");
        }

        return Result.ok("生成进口申请单成功！");
    }

	 /*@AutoLog(value = "主数据—进口申请单-导入关务系统")
	 @ApiOperation(value="主数据—进口申请单-导入关务系统", notes="主数据—进口申请单-导入关务系统")
	 @PostMapping(value = "/importPurchaseSqlServer")
	 public Result<?> importPurchaseSqlServer() {
		 QueryWrapper<MesOrderPurchase> queryWrapper = new QueryWrapper<>();
		 queryWrapper.eq("import_state","0");//是否导入关务系统，若已导入，则为1,反之为0
		 queryWrapper.ne("order_type","库存初始");  //库存初始的不上传关务
		 List<MesOrderPurchase> purchaseList = mesOrderPurchaseService.list(queryWrapper);
		 System.err.println(purchaseList);
		 System.err.println(purchaseList.size());
		 if(purchaseList .size() != 0){
			 for (MesOrderPurchase purchase : purchaseList) {
				 String purchaseId = purchase.getId();
				 QueryWrapper<MesPurchaseItem> wrapper = new QueryWrapper<>();
				 wrapper.eq("purchase_id",purchaseId);
				 List<MesPurchaseItem> purchaseItemList = mesPurchaseItemService.list(wrapper);
				 if(purchaseItemList.size() != 0){
					 int count1 = 0;
					 for (MesPurchaseItem purchaseItem : purchaseItemList) {
						 count1 +=1;
						 //实例化format，格式为“000”
						 Format f1=new DecimalFormat("000");
						 //将1变为001
						 String  count =f1.format(count1);

						 try {
							 // 加载sqlserver的驱动类
							 Class.forName("net.sourceforge.jtds.jdbc.Driver");
							 String url = "jdbc:jtds:sqlserver://192.168.10.80/idb";

							 String username = "sa";//用户名
							 String password = "yzy20170907";//密码
							 try {
								 Connection conn = DriverManager.getConnection(url, username, password);
								 conn.setAutoCommit(false);
								 Statement stmt = conn.createStatement();
								 String sql = "";
								 PreparedStatement ps = null;
								 sql = "INSERT INTO ImpApplyBillDBTemp (id,invoiceNo,imgExgFlag,itemNo,material,optLock,sectionNo,companyCode,uploadDate,price,amount,curr,companyMergerKey,invoiceDate,palletNum,pcs,wrap,containerNo,qty,netWeight,grossWeight,scmCoc) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
								 ps = conn.prepareStatement(sql);
								 ps.setString(1, IdUtil.simpleUUID());//id
								 ps.setString(2, purchase.getOrderCode());//进货单号
								 ps.setString(3, purchaseItem.getImgExgFlag());//物料标记
								 ps.setInt(4, count1);//项号
								 ps.setString(5, purchaseItem.getMaterielCode());//料号
								 ps.setInt(6, 0);//乐观锁
								 SimpleDateFormat Dateformat = new SimpleDateFormat("yyyyMMdd");
								 String dateTime = Dateformat.format(new Date());
								 ps.setString(7, dateTime+"001");//批次号
								 ps.setString(8, "500666002U");//公司编码
								 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
								 String date = formatter.format(new java.util.Date());
								 ps.setString(9, date);//上传时间
								 ps.setString(10, purchaseItem.getGrossPrice());//企业单件
								 ps.setString(11, purchase.getTotalPrice());//企业总价
								 ps.setString(12, purchase.getCurrency());//币制
								 ps.setString(13,"");//企业关键合并key
								 SimpleDateFormat Dateformatter = new SimpleDateFormat("yyyy/M/d");
								 String docketTime = Dateformatter.format(new Date());
								 ps.setString(14, docketTime);//票据日期
								 ps.setString(15, purchaseItem.getPalletNum());//板数
								 ps.setString(16, purchaseItem.getPcs());//件数
								 ps.setString(17, purchaseItem.getWrap());//包装种类
								 ps.setString(18, purchaseItem.getContainerNo());//箱号
								 ps.setString(19, purchaseItem.getPurchaseNum());//企业数量
								 ps.setString(20, purchaseItem.getNetWeight());//净重
								 ps.setString(21, purchaseItem.getGrossWeight());//毛重
								 ps.setString(22, purchase.getSupplierName());//客户/供应商
								 ps.executeUpdate();
								 conn.commit();
								 //设置采购订单主表状态为1：已上传
								 purchase.setImportState("1");
								 mesOrderPurchaseService.updateById(purchase);
								 System.err.println("进口申请单导入完成---");

								 if (ps != null) { // 关闭声明
									 try {
										 ps.close();
									 } catch (SQLException e) {
//										 e.printStackTrace();
										 log.error(e.getMessage(),e);
									 }
								 }
								 if (stmt != null) { // 关闭声明
									 try {
										 stmt.close();
									 } catch (SQLException e) {
//										 e.printStackTrace();
										 log.error(e.getMessage(),e);
									 }
								 }
								 if (conn != null) { // 关闭连接对象
									 try {
										 conn.close();
									 } catch (SQLException e) {
//										 e.printStackTrace();
										 log.error(e.getMessage(),e);
									 }
								 }
							 } catch (SQLException se) {
//								 se.printStackTrace();
								 log.error(se.getMessage(),se);
								 return Result.error("关务系统连接失败！请联系管理员检查！");
							 }
						 } catch (ClassNotFoundException e) {
							 log.error(e.getMessage(),e);
							 return Result.error("找不到驱动程序类 ，加载驱动失败！");
						 }
					 }
				 }else {
					 return Result.error("没有找到采购订单子表的数据！请检查！");
				 }
			 }
		 }else {
			 return Result.ok("数据已全部导入关务系统！");
		 }
		 return Result.ok("关务系统导入成功！");
	 }*/

    /**
     * 添加
     *
     * @param mesOrderPurchase
     * @return
     */
    @AutoLog(value = "订单管理—采购订单-添加")
    @ApiOperation(value = "订单管理—采购订单-添加", notes = "订单管理—采购订单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody MesOrderPurchase mesOrderPurchase) {
        mesOrderPurchaseService.addAll(mesOrderPurchase);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mesOrderPurchase
     * @return
     */
    @AutoLog(value = "订单管理—采购订单-编辑")
    @ApiOperation(value = "订单管理—采购订单-编辑", notes = "订单管理—采购订单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody MesOrderPurchase mesOrderPurchase) {
        mesOrderPurchaseService.updateById(mesOrderPurchase);
        return Result.ok("编辑成功!");
    }

    /**
     * 远程调用，编辑采购订单主表
     *
     * @param mesOrderPurchase
     * @return
     */
    @PutMapping(value = "/editPurchase")
    public String editPurchase(@RequestBody MesOrderPurchase mesOrderPurchase) {
        mesOrderPurchaseService.updateById(mesOrderPurchase);
        return "编辑成功!";
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单管理—采购订单-通过id查询")
    @ApiOperation(value = "订单管理—采购订单-通过id查询", notes = "订单管理—采购订单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        MesOrderPurchase mesOrderPurchase = mesOrderPurchaseService.getById(id);
        if (mesOrderPurchase == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(mesOrderPurchase);

    }

    /**
     * 远程调用，通过id获取采购订单主表的数据
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/getOrderPurchaseById")
    public MesOrderPurchase getOrderPurchaseById(@RequestParam(name = "id", required = true) String id) {
        MesOrderPurchase mesOrderPurchase = mesOrderPurchaseService.getById(id);
        return mesOrderPurchase;

    }

    /**
     * 远程调用，通过采购订单编号模糊搜索数据 返回所有id拼接的字符串
     *
     * @param code
     * @return id, id字符串
     */
    @GetMapping(value = "/getOrderPurchaseLikeCode")
    public List<String> getOrderPurchaseLikeCode(@RequestParam(name = "code", required = true) String code) {
        QueryWrapper<MesOrderPurchase> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("order_code", code);
        List<MesOrderPurchase> list = mesOrderPurchaseService.list(queryWrapper);
        if (list.size() > 0) {
            List<String> nameList = list.stream().map(orderPurchase -> orderPurchase.getId()).collect(Collectors.toList());
            return nameList;
        }
        return new ArrayList<>();
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单管理—采购订单-通过id删除")
    @ApiOperation(value = "订单管理—采购订单-通过id删除", notes = "订单管理—采购订单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        mesOrderPurchaseService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "订单管理—采购订单-批量删除")
    @ApiOperation(value = "订单管理—采购订单-批量删除", notes = "订单管理—采购订单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mesOrderPurchaseService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MesOrderPurchase mesOrderPurchase) {
        return super.exportXls(request, mesOrderPurchase, MesOrderPurchase.class, "订单管理—采购订单");
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MesOrderPurchase.class);
    }
    /*---------------------------------主表处理-end-------------------------------------*/

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单管理—采购订单子表通过主表ID查询")
    @ApiOperation(value = "订单管理—采购订单子表主表ID查询", notes = "订单管理—采购订单子表-通主表ID查询")
    @GetMapping(value = "/queryMesPurchaseItemByMainId")
    public Result<?> queryMesPurchaseItemListByMainId(@RequestParam(name = "id") String id,
                                                      @RequestParam(name = "gauge", required = false) String gauge,
                                                      @RequestParam(name = "materielCode", required = false) String materielCode,
                                                      @RequestParam(name = "ifFinish", required = false) String ifFinish) {
        return mesOrderPurchaseService.queryMesPurchaseItemListByMainId(id, gauge, materielCode, ifFinish);
    }

    @AutoLog(value = "订单管理—采购订单子表通过主表ID查询")
    @ApiOperation(value = "订单管理—采购订单子表主表ID查询", notes = "订单管理—采购订单子表-通主表ID查询")
    @GetMapping(value = "/queryMesPurchaseItemsByMainId")
    public Result<?> queryMesPurchaseItemsByMainId(@RequestParam(name = "id") String id,
                                                   @RequestParam(name = "gauge", required = false) String gauge,
                                                   @RequestParam(name = "materielCode", required = false) String materielCode,
                                                   @RequestParam(name = "ifFinish", required = false) String ifFinish,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<MesPurchaseItem> page = new Page<>(pageNo, pageSize);
        return mesOrderPurchaseService.queryMesPurchaseItemsByMainId(id, gauge, materielCode, ifFinish, page);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单管理—采购订单子表通过主表ID和状态、二维码id 查询")
    @ApiOperation(value = "订单管理—采购订单子表主表ID查询", notes = "订单管理—采购订单子表-通主表ID查询")
    @GetMapping(value = "/queryMesPurchaseItemByMainId2")
    public Result<?> queryMesPurchaseItemListByMainId2(@RequestParam(name = "id", required = true) String id,
                                                       @RequestParam(name = "wholeId", required = true) String wholeId,
                                                       @RequestParam(name = "ifFinish", required = true) String ifFinish) {
        MesStorageWholesale Wholesale = stockClient.findById(wholeId);
        if (Wholesale == null) {
            return Result.error("找不到对应数据！");
        }
        QueryWrapper<MesPurchaseItem> wrapper = new QueryWrapper<>();
        wrapper.eq("purchase_id", id).eq("if_finish", ifFinish).eq("materiel_code", Wholesale.getProductCode());
        List<MesPurchaseItem> mesPurchaseItemList = mesPurchaseItemService.list(wrapper);
        if (mesPurchaseItemList.size() == 0) {
            return Result.error("找不到对应数据!请检查！");
        }
        return Result.ok(mesPurchaseItemList);

    }

    /**
     * 远程调用，通过子表id获取采购订单主表的数据
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/getPurchaseNameById")
    public MesOrderPurchase getPurchaseNameById(@RequestParam(name = "id", required = true) String id) {
        MesPurchaseItem purchaseItem = mesPurchaseItemService.getById(id);
        String purchaseId = purchaseItem.getPurchaseId();
        MesOrderPurchase purchase = mesOrderPurchaseService.getById(purchaseId);
        return purchase;
    }

    /**
     * 远程调用，通过子表id获取采购订单子表的数据
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryMesPurchaseItemById")
    public MesPurchaseItem queryMesPurchaseItemListById(@RequestParam(name = "id", required = true) String id) {
        MesPurchaseItem purchaseItem = mesPurchaseItemService.getById(id);
        return purchaseItem;
    }

    /*--------------------------------子表处理-订单管理—采购订单子表-begin----------------------------------------------*/

    /**
     * 通过主表ID查询
     *
     * @return
     */
    @AutoLog(value = "订单管理—采购订单子表-通过主表ID查询")
    @ApiOperation(value = "订单管理—采购订单子表-通过主表ID查询", notes = "订单管理—采购订单子表-通过主表ID查询")
    @GetMapping(value = "/listMesPurchaseItemByMainId")
    public Result<?> listMesPurchaseItemByMainId(MesPurchaseItem mesPurchaseItem,
                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                 HttpServletRequest req) {
        QueryWrapper<MesPurchaseItem> queryWrapper = QueryGenerator.initQueryWrapper(mesPurchaseItem, req.getParameterMap());
        Page<MesPurchaseItem> page = new Page<MesPurchaseItem>(pageNo, pageSize);
        IPage<MesPurchaseItem> pageList = mesPurchaseItemService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param mesPurchaseItem
     * @return
     */
    @AutoLog(value = "订单管理—采购订单子表-添加")
    @ApiOperation(value = "订单管理—采购订单子表-添加", notes = "订单管理—采购订单子表-添加")
    @PostMapping(value = "/addMesPurchaseItem")
    public Result<?> addMesPurchaseItem(@RequestBody MesPurchaseItem mesPurchaseItem) {
        //if(StringUtils.isNotBlank(mesPurchaseItem.getPurchaseNum())){
        mesPurchaseItem.setUnreceiveNum(mesPurchaseItem.getPurchaseNum());
        //}
        if (StringUtils.isNotBlank(mesPurchaseItem.getPurchaseId())) {
            String purchaseId = mesPurchaseItem.getPurchaseId();
            MesOrderPurchase purchase = mesOrderPurchaseService.getById(purchaseId);
            purchase.setIfFinish("未完成");
            mesOrderPurchaseService.updateById(purchase);
        }
        mesPurchaseItem.setIfFinish("未完成");
        mesPurchaseItemService.save(mesPurchaseItem);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mesPurchaseItem
     * @return
     */
    @AutoLog(value = "订单管理—采购订单子表-编辑")
    @ApiOperation(value = "订单管理—采购订单子表-编辑", notes = "订单管理—采购订单子表-编辑")
    @PutMapping(value = "/editMesPurchaseItem")
    public Result<?> editMesPurchaseItem(@RequestBody MesPurchaseItem mesPurchaseItem) {
        if (StringUtils.isNotBlank(mesPurchaseItem.getPurchaseNum())) {
            if (!"0".equals(mesPurchaseItem.getPurchaseNum())) {
                mesPurchaseItem.setIfFinish("未完成");
            } else {
                mesPurchaseItem.setIfFinish("收货完成");
            }
        }
        mesPurchaseItemService.updateById(mesPurchaseItem);
        return Result.ok("编辑成功!");
    }


    /**
     * 远程调用，编辑采购订单子表数据
     *
     * @param mesPurchaseItem
     * @return
     */
    @PutMapping(value = "/editPurchaseItem")
    public String editPurchaseItem(@RequestBody MesPurchaseItem mesPurchaseItem) {
        mesPurchaseItemService.updateById(mesPurchaseItem);
        return "编辑成功!";
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单管理—采购订单子表-通过id删除")
    @ApiOperation(value = "订单管理—采购订单子表-通过id删除", notes = "订单管理—采购订单子表-通过id删除")
    @DeleteMapping(value = "/deleteMesPurchaseItem")
    public Result<?> deleteMesPurchaseItem(@RequestParam(name = "id", required = true) String id) {
        mesPurchaseItemService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 更新未收货数量
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单管理—采购订单子表-更新未收货数量")
    @ApiOperation(value = "订单管理—采购订单子表-通过id删除", notes = "订单管理—采购订单子表-更新未收货数量")
    @GetMapping(value = "/uploadUnreceiveNum")
    public Result<?> uploadUnreceiveNum(@RequestParam(name = "id", required = true) String id) {
        mesPurchaseItemService.uploadUnreceiveNum(id);
        return Result.ok("更新成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "订单管理—采购订单子表-批量删除")
    @ApiOperation(value = "订单管理—采购订单子表-批量删除", notes = "订单管理—采购订单子表-批量删除")
    @DeleteMapping(value = "/deleteBatchMesPurchaseItem")
    public Result<?> deleteBatchMesPurchaseItem(@RequestParam(name = "ids", required = true) String ids) {
        this.mesPurchaseItemService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportMesPurchaseItem")
    public ModelAndView exportMesPurchaseItem(HttpServletRequest request, MesPurchaseItem mesPurchaseItem) {
        // Step.1 组装查询条件
        QueryWrapper<MesPurchaseItem> queryWrapper = QueryGenerator.initQueryWrapper(mesPurchaseItem, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<MesPurchaseItem> pageList = mesPurchaseItemService.list(queryWrapper);
        List<MesPurchaseItem> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "订单管理—采购订单子表"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, MesPurchaseItem.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("订单管理—采购订单子表报表", "导出人:" + sysUser.getRealname(), "订单管理—采购订单子表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importMesPurchaseItem/{mainId}")
    public Result<?> importMesPurchaseItem(HttpServletRequest request,
                                           HttpServletResponse response,
                                           @PathVariable("mainId") String mainId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<MesPurchaseItem> list = ExcelImportUtil.importExcel(file.getInputStream(), MesPurchaseItem.class, params);
                for (MesPurchaseItem temp : list) {
                    if (StringUtils.isNotBlank(temp.getPurchaseNum())) {
                        temp.setIfFinish("未完成");
                        temp.setUnreceiveNum(temp.getPurchaseNum());
                    }
                    temp.setPurchaseId(mainId);
                }
                MesOrderPurchase purchase = mesOrderPurchaseService.getById(mainId);
                purchase.setIfFinish("未完成");
                mesOrderPurchaseService.updateById(purchase);
                long start = System.currentTimeMillis();
                mesPurchaseItemService.saveBatch(list);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-订单管理—采购订单子表-end----------------------------------------------*/


}
